package cn.neusoft.controller;

import cn.neusoft.domain.*;
import cn.neusoft.exception.AppException;
import cn.neusoft.exception.AppExceptionCodeMsg;
import cn.neusoft.query.InvoiceQuery;
import cn.neusoft.service.InvoiceService;
import cn.neusoft.service.MvpSupplierService;
import cn.neusoft.util.UUIDUtils;
import cn.neusoft.vo.PageBean;
import cn.neusoft.vo.ResultBean;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@RestController // @Controller + @ResponseBody
@RequestMapping(value = "/invoice",produces = "application/json;charset=utf-8")
//接口文档的注解
@Api(value = "财务模块的API",description="发票相关功能")
public class InvoiceController {
  @Autowired
  InvoiceService invoiceService;
  @Autowired
  MvpSupplierService mvpSupplierService;


  @Resource
  private SqlSessionFactory sqlSessionFactory;

  @PostMapping  ("/register")  //   Post + /invoice/register
  @ApiOperation(value = "登记发票" )
  public ResultBean invoiceRegister(@RequestParam Integer num){
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);    //  反射获取，获取Mapper
    for (int i = 0 ; i < num ; i++){
      Invoice invoice=new Invoice();
      Date update_time=new Date(System.currentTimeMillis());
      invoice.setUpdate_time(update_time);
      invoiceService.invoiceRegister(invoice);
    }
    sqlSession.commit();
    sqlSession.close();
   return ResultBean.success();
  }

  @PutMapping("/usage")//   Put + /invoice/usage
  @ApiOperation(value = "领用发票" )
  public ResultBean invoiceUsage(@RequestBody Invoice invoice) throws Exception {
    if(StringUtils.isEmpty(invoice.getInvoice_task_id())){
      throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
    }
    String task_id=invoice.getInvoice_task_id();
    Task task=invoiceService.findUsageInfo(task_id);
    Integer invoice_id=invoiceService.findInvoiceID();
    if(invoice_id==null){
      return ResultBean.nonregister();
    }
    if(!invoiceService.findIfUsage(task_id)){
      return ResultBean.haveusage();
    }
    invoice.setInvoice_substation_id(task.getSubstation_id());
    invoice.setInvoice_order_id(task.getOrder_id());
    invoice.setInvoice_amount(task.getDelivery_fee().add(task.getPrice().multiply(BigDecimal.valueOf(task.getAmount()))));
    invoice.setInvoice_operator_id(task.getCustomer_id());
    invoice.setInvoice_operator_name(task.getCustomer_name());
    invoice.setInvoice_status("1");
    invoice.setInvoice_id(invoice_id);
    Date update_time=new Date(System.currentTimeMillis());
    invoice.setUpdate_time(update_time);
    invoiceService.invoiceUsage(invoice);

    //打印发票
    String TEMP_PATH="E:\\logistics\\Static\\invoiceModel.pdf";
    String OUT_PATH="E:\\logistics\\Static\\outPut\\"+invoice.getInvoice_task_id()+".pdf";
    String FONT_PATH="E:\\logistics\\Static\\Fonts\\simsun.ttc,0";
    PdfDocument pdfDocument= new PdfDocument(new PdfReader(TEMP_PATH),new PdfWriter(OUT_PATH));
    PdfAcroForm form=PdfAcroForm.getAcroForm(pdfDocument,false);
    PdfFont font =PdfFontFactory.createFont(FONT_PATH);
    DeviceRgb color=new DeviceRgb(0,0,0);
    //文本填充
    Customer customer=invoiceService.findCustomerByID(invoice.getInvoice_operator_id());
    SimpleDateFormat update_date = new SimpleDateFormat("yyyy-MM-dd");
    Commodity commodity=mvpSupplierService.findCommodity(task.getCommodity_id());
    Supplier supplier=invoiceService.findSupplier(commodity.getSupplier_id());
    HashMap<String,String> map=new HashMap<>();
    map.put("invoice_code","747167897084876888");
    String invoice_num= String.valueOf(invoice.getInvoice_id());
    map.put("invoice_num",invoice_num);
    map.put("customer_name",invoice.getInvoice_operator_name());
    map.put("address",task.getReceive_addr());
    map.put("tel",customer.getCustomer_tel());
    map.put("commodity_name",task.getCommodity_name());
    map.put("measure",commodity.getMeasure());
    map.put("price2", String.valueOf(task.getDelivery_fee()));
    map.put("totalamount2",String.valueOf(task.getDelivery_fee()));
    map.put("amount",String.valueOf(task.getAmount()));
    map.put("price", String.valueOf(task.getPrice()));
    map.put("totalamount",String.valueOf(invoice.getInvoice_amount().subtract(task.getDelivery_fee())));
    map.put("update_date",update_date.format(invoice.getUpdate_time()));
    map.put("sum", String.valueOf(invoice.getInvoice_amount()));
    map.put("supply_name",supplier.getSupplier_name());
    map.put("supply_addr",supplier.getSupplier_addr());
    map.put("supply_tel",supplier.getSupplier_tel());
    map.put("me","杰哥速递物流公司");
    System.out.println(update_date);
    for(Map.Entry<String,String> entry:map.entrySet()){
      form.getFormFields().get(entry.getKey()).setValue(entry.getValue()).setColor(color).setFont(font);
    }

//    uploadService.UploadByStream();
    //清除表单域
    form.flattenFields();
    pdfDocument.close();

    //上传到七牛云
    invoiceService.UploadToQiNiuYun(OUT_PATH, UUIDUtils.getUUID(),invoice);

    return ResultBean.success(invoice);
  }




  @PutMapping("/return")//   Put + /invoice/return
  @ApiOperation(value = "退回发票" )
  public ResultBean returnInvoice(@RequestBody Invoice invoice){
    Date update_time=new Date(System.currentTimeMillis());
    invoice.setUpdate_time(update_time);
    if(Objects.equals(invoice.getInvoice_status(), "0")||Objects.equals(invoice.getInvoice_status(), "3")){
      return ResultBean.dontusage();
    }
    invoiceService.returnInvoice(invoice);
    return ResultBean.success();
  }

  @PutMapping("/discard")//   Put + /invoice/discard
  @ApiOperation(value = "废弃发票" )
  public ResultBean discardInvoice(@RequestBody Invoice invoice){
    Date update_time=new Date(System.currentTimeMillis());
    invoice.setUpdate_time(update_time);
    invoiceService.discardInvoice(invoice);
    return ResultBean.success();
  }

  @PostMapping("/page")  //  Post + /invoice/page
  @ApiOperation(value = "分页查询发票信息" )
  public ResultBean findByPage(@RequestBody InvoiceQuery invoiceQuery){
    PageBean<Invoice> pageBean = invoiceService.findByPage(invoiceQuery);
    return ResultBean.success(pageBean);
  }

  @GetMapping("/reinvoice")
  @ApiOperation(value = "查询可领用发票的数量")
  public ResultBean findReInvoice(){
    return ResultBean.success(invoiceService.findReInvoice()+invoiceService.findReturnInvoice());
  }
  @GetMapping("/havainvoice")
  @ApiOperation(value = "查询已领用发票的数量")
  public ResultBean findHaveInvoice(){
    return ResultBean.success(invoiceService.findHaveInvoice());
  }
  @GetMapping("/returninvoice")
  @ApiOperation(value = "查询已退回发票的数量")
  public ResultBean findReturnInvoice(){
    return ResultBean.success(invoiceService.findReturnInvoice());
  }
  @GetMapping("/discardinvoice")
  @ApiOperation(value = "查询废弃发票的数量")
  public ResultBean findDiscardInvoice(){
    return ResultBean.success(invoiceService.findDiscardInvoice());
  }

  @GetMapping("/findcommodity")
  @ApiOperation(value = "查询商品")
  public ResultBean findCommodity(){
    return ResultBean.success(invoiceService.findCommodity());
  }

  @PostMapping("/findPdf")
  @ApiOperation(value = "查找pdf路径")
  public ResultBean findPdf(@RequestBody InvoicePdf invoicePdf){
    return ResultBean.success(invoiceService.findPdf(invoicePdf));
  }
}
